package com.artifact.mit.mypoint.service.async;

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

import android.content.Context;
import android.content.ContextWrapper;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ListView;

import com.artifact.mit.mypoint.activity.MyPointBaseActivity;
import com.artifact.mit.mypoint.adapter.ProductListAdapter;
import com.artifact.mit.mypoint.service.ServiceHandler;
import com.artifact.mit.mypoint.service.model.api.ProductItem;

public class ProductListAsync extends AsyncTask<String, Void, ProductItem> {
	
	private Context ctx;
	private ListView listView;
	private ServiceHandler serviceHandler;
	
	void setProgress(int visibility){
		MyPointBaseActivity activity = ((MyPointBaseActivity) ctx);
		if (activity != null)
			activity.setProgressBar(visibility);
	}
	
	public ProductListAsync(Context ctx, ListView listView) {
		this.ctx = ctx;
		this.listView = listView;
		this.serviceHandler = new ServiceHandler(ctx);
	}
	@Override
	protected void onPreExecute() {
		setProgress(View.VISIBLE);
	}
	@Override
	protected ProductItem doInBackground(String... arg0) {
		try {
			ProductItem item = serviceHandler.productListByCatalogue(arg0[0]);
			ContextWrapper cw = new ContextWrapper(ctx);
			File directory = cw.getDir("dat", Context.MODE_PRIVATE);
			File file = new File(directory, "product.ser");
			FileOutputStream f = new FileOutputStream(file);
			ObjectOutputStream s = new ObjectOutputStream(f);
			s.writeObject(item);
			s.close();
			return item;
		} catch (Exception e) {
			Log.e(this.getClass().getName(), "Error Loading Product", e);
		}
		return null;
	}
	
	@Override
	protected void onPostExecute(ProductItem result) {
		ProductListAdapter adapter = new ProductListAdapter(ctx);
		for(ProductItem.ProductItemDetail pid: result.getProductItemDetails()){
			adapter.add(pid);
		}
		listView.setAdapter(adapter);
		setProgress(View.GONE);
	}
}
